package com.htudata.zabbix.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htudata.core.util.HttpURLConnectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BaseZabbixApiService {

  private static String AUTH = null;
  
  @Value("${zabbix.url}")
  private String zabbix_api_url;
  
  @Value("${zabbix.user}")
  private String zabbix_user;
  
  @Value("${zabbix.pwd}")
  private String zabbix_pswd;

  public String getJSONResult(JSONObject request) throws Exception {
    String result = sendPost(request);
    if (result == null) {
      return null;
    } 
    return result;
  }
  
  @Deprecated
  public JSONObject getJSONObjectResult(JSONObject request) throws Exception {
    String response = "";
    try {
      response = sendPost(request);
      JSONObject result = JSON.parseObject(response).getJSONObject("result");
      if (result != null)
        return result; 
      JSONObject error = JSON.parseObject(response).getJSONObject("error");
      return null;
    } catch (Exception e) {
       throw e;
    } 
  }
  
  @Deprecated
  public JSONArray getJSONArrayResult(JSONObject request)throws Exception {
    String response = "";
    try {
      response = sendPost(request);
      JSONArray result = JSON.parseObject(response).getJSONArray("result");
      if (result != null)
        return result; 
      JSONArray error = JSON.parseObject(response).getJSONArray("error");
      return null;
    } catch (Exception e) {
       throw e;
    } 
  }
  
  public String sendPost(JSONObject request)throws Exception {
    request.put("auth", getAuth());
    if (request.get("auth") == null)
      return null; 
    String requestJson = JSON.toJSONString(request);
    return HttpURLConnectionUtils.sendPost(this.zabbix_api_url, requestJson);
  }
  
  private String getAuth() throws Exception{
    if (AUTH == null)
      setAuth(); 
    return AUTH;
  }
  
  private void setAuth() throws Exception{
    JSONObject params = new JSONObject();
    params.put("user", this.zabbix_user);
    params.put("password", this.zabbix_pswd);
    JSONObject request = new JSONObject();
    request.put("jsonrpc", "2.0");
    request.put("method", "user.login");
    request.put("params", params);
    request.put("auth", null);
    request.put("id", Integer.valueOf(0));
    String requestJson = JSON.toJSONString(request);
    String response = HttpURLConnectionUtils.sendPost(this.zabbix_api_url, requestJson);
    JSONObject json = JSON.parseObject(response);
    if (json != null)
      AUTH = json.getString("result"); 
  }
}
